<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button>随机生成地址</button>
<p></p>
<script>
    let op = document.querySelector('p')
    let btn = document.querySelector('button')

    function httpRequest(api, callBack, methods = 'get') {
        return new Promise((resolve, reject) => {
            let http = new XMLHttpRequest()
            let baseURL = 'https://api.i-lynn.cn'
            http.addEventListener('readystatechange', function () {
                if (http.readyState === 4) {
                    if (http.status === 200) {
                        arr = JSON.parse(http.response)
                        resolve(arr)
                    } else {
                        reject('错误')
                    }
                }
            })
            //连接地址
            http.open(methods, baseURL + api)
            //发送数据
            http.send()
        })
    }

    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min)
    }
    //随机获取数组的值
    function getRandomArr(arr) {
        return arr[getRandomInt(0, arr.length - 1)]
    }

    //定义循环变量
    let resArr, resX, num = 0, nl = '', array = [],m=0;
    async function call(array,callBack) {
        resArr ? resX = ('?id=' + resArr.id) : resX = '';
        let res = await httpRequest('/area' + resX)
        resArr = getRandomArr(res)
        if (!resArr) {
            m++
            callBack && callBack();
            return
        }
        array.push(resArr.name)
        console.log(resArr.name)
        call(array,callBack)

    }
    let boll=false;
    btn.addEventListener('click', () => {
        if(boll) return
        boll=true
        array= []
        nl=''
        let start=Date.now();
        call(array,()=>{
            for ( let i = 0; i < array.length; i++) {
                if (i + 1 === array.length) {
                    nl += array[i]
                } else {
                    nl += array[i] + '->'
                }
            }
            op.innerHTML = "地址订单为:"+nl
            boll=false
            let end=Date.now();
            console.log(start+'ms');

            console.log('程序运行时间:'+(end-start)+'ms');
        })

    })

</script>

</body>
</html>